package backend.Instruction;

import backend.Register.RISCVoperand;
import backend.Register.virtualFReg;

import java.util.ArrayList;
import java.util.List;

public class RISCVload extends RISCVinst {
    private String type;
    private List<RISCVoperand> operands = new ArrayList<>();

    public RISCVload(List<RISCVoperand> operands, String type) {
        this.operands = operands;
        this.type = type;
        setDst(operands.get(0));
        setAddress(operands.get(1));
        setOffset(operands.get(2));
    }

    public void setDst(RISCVoperand dst) {
        setDefReg(operands.get(0), dst);
        operands.set(0, dst);
    }

    public void setAddress(RISCVoperand address) {
        addUseReg(operands.get(1), address);
        operands.set(1, address);
    }

    public void setOffset(RISCVoperand offset) {
        addUseReg(operands.get(2), offset);
        operands.set(2, offset);
    }

    public RISCVoperand getAddress() {
        return operands.get(1);
    }

    public RISCVoperand getDst() {
        return operands.get(0);
    }

    public RISCVoperand getOffset() {
        return operands.get(2);
    }

    @Override
    public void replaceReg(RISCVoperand oldReg, RISCVoperand newReg) {
        if (operands.get(0).equals(oldReg)) {
            setDst(newReg);
        }
        if (operands.get(1).equals(oldReg)) {
            setAddress(newReg);
        }
        if (operands.get(2) != null && operands.get(2).equals(oldReg)) {
            setOffset(newReg);
        }
    }

    @Override
    public String toString() {
        StringBuilder output = new StringBuilder();
        output.append(type).append(" ").append(operands.get(0));
        output.append(", ").append(operands.get(2)).append("(").append(operands.get(1)).append(")");
        // 如果是浮点数寄存器 加载的时候需要变成 fld
        if (operands.get(0) instanceof virtualFReg) {
            output.insert(0, "f");
        }
        output.append("\n");
        return output.toString();
    }
}
